// pages/category/main.js
import {request} from "../../request/index"
import regeneratorRuntime from "../../lib/runtime/runtime";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    leftMenuList: [],
    rightContent: [],
    //点击active
    currentIndex: 0,
    //右侧滚动至顶部
    scrollTop: 0
  },
  //接口的返回数据
  Cates: [],
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    //缓存数据
    //先判断本地存储有没有数据
    let Cates = wx.getStorageSync("cates");
    if (!Cates) {
      this.getCate()
    } else {
      //有旧数据 定义过期时间 10s 改成5min
      if (Date.now() - Cates.time > 1000 * 10) {
        this.getCate()
      } else {
        //使用旧数据
        this.Cates = Cates.data
         //遍历左侧数据
      let leftMenuList = this.Cates.map(v => v.cat_name)
      let rightContent = this.Cates[0].children
      this.setData({
        leftMenuList,
        rightContent
      })
      }
    }

  },
  async getCate() {
    // request({
    //   url: '/categories'
    // })
    // .then(res => {
    //   this.Cates = res.data.message

    //   //把数据存入到本地
    //   wx.setStorageSync("cates", {time: Date.now(), data:this.Cates});

    //   //遍历左侧数据
    //   let leftMenuList = this.Cates.map(v => v.cat_name)
    //天上地下唯我徐晓林

    //   //遍历右侧数据
    //   let rightContent = this.Cates[0].children
    //   this.setData({
    //     leftMenuList,
    //     rightContent
    //   })
    // })

    let res = await request({url: '/categories'})
    // this.Cates = res.data.message
    this.Cates = res

    //把数据存入到本地
    wx.setStorageSync("cates", {time: Date.now(), data:this.Cates});

      //遍历左侧数据
    let leftMenuList = this.Cates.map(v => v.cat_name)

      //遍历右侧数据
    let rightContent = this.Cates[0].children
    this.setData({
      leftMenuList,
      rightContent
    })  
  },
  //左侧菜单点击事件
  isActive(e) {
    let {index} = e.currentTarget.dataset
    let rightContent = this.Cates[index].children

    this.setData({
      currentIndex: index,
      rightContent,
      // 重新设置scrollTop距离为0
      scrollTop: 0
    })
  }
    
})